package com.zsd.android.arouter_api;

import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.util.LruCache;

/**
 * 参数Parameter加载管理器
 */
public class ParameterManager {

    //APT生成获取参数类文件，后缀名
    private static final String FILE_SUFFIX_NAME = "$$Parameter";

    private static volatile ParameterManager instance;
    //Lru缓存，key：类名；value：参数Parameter加载接口
    private LruCache<String, IParameterLoad> cache;

    private ParameterManager() {
        // 初始化，并赋值缓存中条目的最大值
        cache = new LruCache<>(163);
    }

    public static ParameterManager getInstance() {
        ParameterManager manager = instance;
        if (manager == null) {
            synchronized (PackageManager.class) {
                if (manager == null) {
                    manager = new ParameterManager();
                    instance = manager;
                }
            }
        }
        return manager;
    }

    public void loadParameter(@NonNull Object target) {
        String className = target.getClass().getName();
        IParameterLoad iParameter = cache.get(className);

        try {
            //缓存找不到
            if (iParameter == null) {
                Class<?> clazz = Class.forName(className + FILE_SUFFIX_NAME);
                iParameter = (IParameterLoad) clazz.newInstance();
                cache.put(className, iParameter);
            }
            iParameter.loadParameter(target);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
